#include "tuling_robot.h"

#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>

Tuling_Robot::Tuling_Robot(Http_Post *parent) :
	Http_Post(parent)
{

}

Tuling_Robot::~Tuling_Robot()
{

}

void Tuling_Robot::post(QString group_id, QString user_id, QString context)
{
	m_userid = group_id.isEmpty() ? user_id : group_id;

	QString json_context("{\"reqType\":0,\"perception\": {\"inputText\": {\"text\": \"");
	json_context += context;
	json_context += "\"}},\"userInfo\": {\"apiKey\": \"c208187ef20f424b9539b3ff6e7b146d\",\"userId\": \"c208187ef20f424b9539b3ff6e7b146d\", \"groupId\":\"";
	json_context += group_id;
	json_context += "\", \"userIdName\":\"";
	json_context += user_id;
	json_context += "\"}}";

    //qDebug() << "ROBOT:" << json_context;

	Http_Post::post("http://openapi.tuling123.com/openapi/api/v2", json_context);
}

void Tuling_Robot::finished(QNetworkReply* reply)
{
	QString replyStr(reply->readAll());

	if (replyStr == "")
		return;

#if 0//QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
	qDebug() << "DEBUG:" << replyStr;
#endif

	QJsonDocument doc = QJsonDocument::fromJson(replyStr.toUtf8());
	if (!doc.isObject()) {
		return;
	}

	QJsonObject obj = doc.object();
	QJsonArray arr = obj["results"].toArray();

	Q_FOREACH (const QJsonValue & val, arr) {
		QJsonObject result = val.toObject();
		QJsonObject text = result["values"].toObject();

		QString context = text["text"].toString();

		Q_EMIT respond(m_userid, context);
	}
}
